#!/bin/bash
function uninit()
{
    echo -ne "\a"
    rm -rf $w
    echo
}
w=$(mktemp -d)
if [ -n "$1" ]  ; then
    I="$1"
    test -n "$I" -a -f "$I"  || { echo "give at least one parmeter - film name" ; exit 1 ; }
    S="$2"
    O=${3:-$(basename $I .avi).mp4}
else
    I=`zenity --file-selection --title="plik z filmem"`
    if [ "-z" "$I" ] ; then
	exit 1
    fi
    S=`zenity --file-selection --title="napis"`
    O=`zenity --entry --title="plik wyjsciowy"`.mp4
    if [ "-z" "$O" ] ; then
	exit 1
    fi
fi
echo ${PROFILE:=k800}
trap uninit EXIT
mkfifo $w/tran.avi

mplayer -identify -endpos 0:0  "$I" -vo null -ao null 2> /dev/null | grep -e "^[^= ]*=[^= ]*$" > $w/ident
. $w/ident
echo $ID_VIDEO_BITRATE
echo $ID_AUDIO_NCH


if [ $ID_VIDEO_BITRATE -ge 300000 ] ; then
    br=300
else
    br=$[$ID_VIDEO_BITRATE / 1000]
fi
mr=$[$br + 20]

mencoder ${S:+-sub "$S"} -profile p320raw -oac copy -ovc raw -o $w/tran.avi "$I"  &
sleep 1
if [[ $ID_AUDIO_NCH = 1 ]] ; then
cat $w/tran.avi  | ffmpeg -y -i - -f mp4 -vol 650 -vcodec xvid -maxrate $mr -b $br -qmin 3 -qmax 5 -bufsize 4096 -g 300 -ac 1 -acodec aac -ab 32  "$O"  
elif [[ $ID_AUDIO_NCH = 2 ]] ; then
cat $w/tran.avi  | ffmpeg -y -i - -f mp4 -vol 650 -vcodec xvid -maxrate $mr -b $br -qmin 3 -qmax 5 -bufsize 4096 -g 300 -acodec aac -ab 64  "$O"  
else
cat $w/tran.avi  | ffmpeg -y -i - -f mp4 -vol 650 -vcodec xvid -maxrate $mr -b $br -qmin 3 -qmax 5 -bufsize 4096 -g 300 -an  "$O"  
fi

wait
